from flask import Blueprint, render_template, request, jsonify
from marshmallow import INCLUDE
from sqlalchemy.sql.elements import or_

from applications.common import curd
from applications.common.curd import up_status
from applications.common.utils.http import success_api, fail_api
from applications.common.utils.rights import authorize
from applications.common.utils import validate
from applications.extensions import db
from applications.models import Category, User
from applications.schemas import CategorySchema

category_bp = Blueprint('admincategory', __name__, url_prefix='/admin/category')


def register_dept_views(app):
    app.register_blueprint(category_bp)


@category_bp.get('/')
@authorize("admin:category:main", log=True)
def main():
    return render_template('admin/category/main.html')


@category_bp.get('/data')
@authorize("admin:category:main", log=True)
def data():
    category = Category.query.order_by(Category.sort).all()
    power_data = curd.model_to_dicts(schema=CategorySchema, data=category)
    res = {
        "data": power_data
    }
    return jsonify(res)


@category_bp.get('/add')
@authorize("admin:category:add", log=True)
def add():
    return render_template('admin/category/add.html', category="")


@category_bp.get('/tree')
@authorize("admin:category:main", log=True)
def tree():
    category = Category.query.filter(Category.status==1).order_by(Category.sort).all()
    category_data = curd.model_to_dicts(schema=CategorySchema, data=category)
    res = {
        "status": {"code": 200, "message": "默认"},
        "data": category_data
    }
    return jsonify(res)


@category_bp.get('/tree/<int:_pid>')
@authorize("admin:category:main", log=True)
def treebypid(_pid):
    category = Category.query.filter(Category.parent_id == _pid).all()
    for item in category:
        item.parent_id = 0
    category_data = curd.model_to_dicts(schema=CategorySchema, data=category)
    res = {
        "status": {"code": 200, "message": "默认"},
        "data": category_data
    }
    return jsonify(res)


@category_bp.post('/save')
@authorize("admin:category:add", log=True)
def save():
    req = request.json
    validate.check_data(CategorySchema(unknown=INCLUDE), req)
    categoryName = validate.xss_escape(req.get("categoryName"))
    parentId = validate.xss_escape(req.get("parentId"))
    sort = validate.xss_escape(req.get("sort"))
    status = validate.xss_escape(req.get("status"))
    remark = validate.xss_escape(req.get("remark"))
    category = Category(
        parent_id=parentId,
        category_name=categoryName,
        sort=sort,
        status=status,
        remark=remark
    )
    db.session.add(category)
    db.session.commit()
    return success_api(msg="成功")


@category_bp.get('/edit')
@authorize("admin:category:edit", log=True)
def edit():
    _id = request.args.get("categoryId")
    category = curd.get_one_by_id(model=Category, id=_id)
    return render_template('admin/category/add.html', category=category)


# 启用
@category_bp.put('/enable')
@authorize("admin:category:edit", log=True)
def enable():
    _id = request.json.get('categoryId')
    _status = request.json.get('status')
    if _id:
        res = up_status(model=Category, id=_id, status=_status)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="操作成功")
    return fail_api(msg="数据错误")


@category_bp.put('/update')
@authorize("admin:category:edit", log=True)
def update():
    json = request.json
    validate.check_data(CategorySchema(unknown=INCLUDE), json)
    id = json.get("categoryId"),
    data = {
        "category_name": validate.xss_escape(json.get("categoryName")),
        "parent_id": validate.xss_escape(json.get("parentId")),
        "sort": validate.xss_escape(json.get("sort")),
        "status": validate.xss_escape(json.get("status")),
        "remark": validate.xss_escape(json.get("remark"))
    }
    d = Category.query.filter_by(id=id).update(data)
    if not d:
        return fail_api(msg="更新失败")
    db.session.commit()
    return success_api(msg="更新成功")


@category_bp.delete('/remove/<int:_id>')
@authorize("admin:category:remove", log=True)
def remove(_id):
    d = Category.query.filter_by(id=_id).delete()
    if not d:
        return fail_api(msg="删除失败")
    db.session.commit()
    return success_api(msg="删除成功")
